//
//  CameraManager.swift
//  replaykit
//
//  Created by zhang on 2025/7/31.
//

import AVFoundation
import SwiftUI

class CameraManager: ObservableObject {
    let session = AVCaptureSession()
    var previewLayer: AVCaptureVideoPreviewLayer?
    
    @Published var isCameraReady = false
    @Published var errorMessage: String?
    
    init() {
        print("CameraManager: 初始化相机管理器")
    }
    
    func setupCamera() {
        print("CameraManager: 开始设置相机")
        
        // 检查权限
        checkCameraPermission { [weak self] granted in
            DispatchQueue.main.async {
                if granted {
                    self?.configureCamera()
                } else {
                    print("CameraManager: 相机权限被拒绝")
                    self?.errorMessage = "相机权限被拒绝"
                }
            }
        }
    }
    
    private func checkCameraPermission(completion: @escaping (Bool) -> Void) {
        print("CameraManager: 检查相机权限")
        
        switch AVCaptureDevice.authorizationStatus(for: .video) {
        case .authorized:
            print("CameraManager: 相机权限已授权")
            completion(true)
        case .notDetermined:
            print("CameraManager: 请求相机权限")
            AVCaptureDevice.requestAccess(for: .video) { granted in
                print("CameraManager: 权限请求结果: \(granted)")
                completion(granted)
            }
        case .denied, .restricted:
            print("CameraManager: 相机权限被拒绝或受限")
            completion(false)
        @unknown default:
            print("CameraManager: 未知权限状态")
            completion(false)
        }
    }
    
    private func configureCamera() {
        print("CameraManager: 配置相机设备")
        
        // 检查是否在模拟器环境中
        #if targetEnvironment(simulator)
        print("CameraManager: 检测到模拟器环境")
        DispatchQueue.main.async {
            self.errorMessage = "模拟器不支持相机功能，请在真机上测试"
        }
        return
        #endif
        
        // 获取后置相机
        guard let device = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back) else {
            print("CameraManager: 无法获取后置相机设备")
            self.errorMessage = "无法获取相机设备"
            return
        }
        
        print("CameraManager: 成功获取相机设备: \(device.localizedName)")
        
        // 创建输入
        guard let input = try? AVCaptureDeviceInput(device: device) else {
            print("CameraManager: 无法创建相机输入")
            self.errorMessage = "无法创建相机输入"
            return
        }
        
        // 在后台线程配置session
        DispatchQueue.global(qos: .userInitiated).async { [weak self] in
            guard let self = self else { return }
            
            // 开始配置session
            self.session.beginConfiguration()
            
            // 添加到session
            self.session.addInput(input)
            
            // 提交配置
            self.session.commitConfiguration()
            
            print("CameraManager: 相机配置完成")
            
            // 在主线程通知UI相机已准备就绪
            DispatchQueue.main.async {
                self.isCameraReady = true
                print("CameraManager: 相机准备就绪，通知UI更新")
            }
        }
    }
    
    func startSession() {
        print("CameraManager: 启动相机会话")
        
        // 确保在主线程外启动会话
        DispatchQueue.global(qos: .userInitiated).async { [weak self] in
            guard let self = self else { return }
            
            // 如果session还没有运行，则启动
            if !self.session.isRunning {
                self.session.startRunning()
                print("CameraManager: 相机会话已启动")
                
                // 在主线程更新状态
                DispatchQueue.main.async {
                    print("CameraManager: 会话启动完成，UI应该能看到预览画面")
                    
                    // 延迟一下再通知UI更新，确保会话完全启动
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
                        print("CameraManager: 最终通知UI更新")
                    }
                }
            } else {
                print("CameraManager: 相机会话已经在运行")
            }
        }
    }
    
    func stopSession() {
        print("CameraManager: 停止相机会话")
        DispatchQueue.global(qos: .userInitiated).async { [weak self] in
            self?.session.stopRunning()
            print("CameraManager: 相机会话已停止")
        }
    }
} 